package nc.hw;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.stream.Collectors;

public class HJ42 {

    private static String toEnglish(long num) {
        if (num == 0) {
            return "zero";
        }
        String[] dw = new String[]{"", "thousand", "million", "billion"};
        // 0-999的读法解析
        int i = 0;
        Stack<String> strings = new Stack<>();
        while (num != 0) {
            long l = num % 1000;
            if (l != 0) {
                if (!"".equals(dw[i])) {
                    strings.push(dw[i]);
                }
                strings.push(less1000English((int) l));
            }
            num = num / 1000;
            i ++;
        }
        StringBuilder sb = new StringBuilder();
        while (!strings.empty()) {
            String pop = strings.pop();
            sb.append(pop);
            if (!strings.empty()) {
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    private static String less1000English(int num) {
        // 1000以下读法解析
        // 首先映射0-19映射关系
        String[] numMatchEng1 = new String[]{
                "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
                "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"
        };
        String[] numMatchEng2 = new String[]{
          "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
        };
        int n100 = num / 100;
        List<String> strings = new ArrayList<>();
        if (n100 != 0) {
            strings.add(numMatchEng1[n100]);
            strings.add("hundred");
        }
        int nless100 = num % 100;
        if (nless100 == 0) {
            return String.join(" ", strings);
        }
        if (n100 != 0) {
            strings.add("and");
        }
        if (nless100 < 20) {
            strings.add(numMatchEng1[nless100]);
        } else {
            // 分成两个数
            strings.add(numMatchEng2[nless100 / 10 - 2]);
            if (nless100 % 10 != 0) {
                strings.add(numMatchEng1[nless100 % 10]);
            }
        }
        return String.join(" ", strings);
    }

    public static void main(String[] args) {
        System.out.println(toEnglish(1652510));
        System.out.println(toEnglish(486669));
        System.out.println(toEnglish(8000));
        System.out.println(toEnglish(1234));
        System.out.println(toEnglish(100));
        System.out.println(toEnglish(9001000));
    }

}
